<template>
  <div class="purchase-container">
    <div class="purchase-padding" v-loading="state.loading">
      <section class="ksn-page-head">
        <section class="balance-poul">
          <div class="top">
            <div class="title">经销商：
              <el-select style="width:250px" v-model="state.subId" placeholder="请选择" filterable @change="changeType">
                <el-option v-for="item in state.subIdList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </div>
          </div>
          <div class="main">
            <div class="priceBox" >
              <div class="priceBox-left">
                <p>资金池余额</p>
                <div class="btnlist">
                  <span class="price">￥{{ state.baseform.balance }}</span>
                </div>
              </div>
              <div class="priceBox-right">
                <div class="priceButton">
                  <el-button v-auth="'DealerCapitalPoolIn'" type="primary" class="view w80"
                    @click="changePrice('IN', 'BALANCE')">充值</el-button>
                </div>
              </div>
            </div>

            <div class="priceBox">
              <div class="priceBox-left">
                <p>基础返利池余额</p>
                <div class="btnlist">
                  <span class="price">￥{{ state.baseform.rebate }}</span>
                </div>
                <div>每单可使用比例： {{ state.baseform.percent }}%</div>
              </div>
              <div class="priceBox-right">
                <div class="rebate">
                  <div class="scrollbar">
                    <el-scrollbar height="100px">
                      <div v-for="item in rebateList" :key="item.id" class="rebate-item">
                        <div class="blue-dot"></div>
                        <span class="text-blue">{{ formatTime(item.time) }}&nbsp;&nbsp;{{ item.type }}&nbsp;&nbsp;{{
                          formatAmount(item) }}</span>
                      </div>
                    </el-scrollbar>
                  </div>
                </div>
              </div>
            </div>

            <div class="priceBox" v-if="state.baseform.jdRebate">
              <div class="priceBox-left">
                <p>京东返利池余额</p>
                <div class="btnlist">
                  <span class="price">￥{{ state.baseform.jdRebate }}</span>
                </div>
                <div>每单可使用比例： {{ state.baseform.jdRebatePercent }}%</div>
              </div>
              <div class="priceBox-right">
                <div class="rebate">
                  <div class="scrollbar">
                    <el-scrollbar height="100px">
                      <div v-for="item in rebateList" :key="item.id" class="rebate-item">
                        <div class="blue-dot"></div>
                        <span class="text-blue">{{ formatTime(item.time) }}&nbsp;&nbsp;{{ item.type }}&nbsp;&nbsp;{{
                          formatAmount(item) }}</span>
                      </div>
                    </el-scrollbar>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
        <el-form ref="searchInfoRef" :model="searchInfo" label-width="140px" class="query-area_forms">
          <el-form-item label="变更金额类型" prop="balanceType">
            <el-select v-model="searchInfo.balanceType" placeholder="全部">
              <el-option v-for="item in TypeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="资金出入账类型" prop="capitalType">
            <el-select v-model="searchInfo.capitalType" placeholder="全部">
              <el-option v-for="item in returnTypeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="处理事项" prop="dealTypes">
            <el-select v-model="searchInfo.dealTypes" placeholder="全部" multiple collapse-tags collapse-tags-tooltip>
              <el-option v-for="item in returnStatus" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="关联订单号" prop="orderNo">
            <el-input v-model="searchInfo.orderNo" placeholder="支持模糊搜索" />
          </el-form-item>
          <el-form-item label="关联售后单号" prop="afterSaleNo">
            <el-input v-model="searchInfo.afterSaleNo" placeholder="支持模糊搜索" />
          </el-form-item>
          <el-form-item label="处理时间">
            <el-date-picker v-model="time" type="daterange" value-format="YYYY-MM-DD" range-separator="-"
              start-placeholder="开始时间" end-placeholder="结束时间" />
          </el-form-item>
        </el-form>
        <div class="system-user-search mgtb15">
          <div style="float: right">
            <el-button type="primary" class="ml10 view" @click="onQuery">查询</el-button>
            <el-button type="primary" class="ml10 view" @click="onReset">重置</el-button>
          </div>
        </div>
      </section>
      <NewTable :tableHead="tableHead" :tableData="state.tableData" :showSortIndex="true" :searchInfo="searchParm"
        :total="state.total" @clickFirst="onLook">
      </NewTable>
      <section class="ksn-page-pagination">
        <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" :pager-count="5"
          :page-sizes="[10, 20, 50, 100]" v-model:current-page="searchParm.page" background
          v-model:page-size="searchParm.size" layout="total, sizes, prev, pager, next, jumper" :total="state.total">
        </el-pagination>
      </section>
      <ReChargeDialog ref="chargeRef" @refresh="getTableData()" />
      <OrderDialog ref="OrderDialogRef" />
      <AfterOrderDialog ref="AfterOrderDialogRef" />
      <financeDetailDialog ref="financeDeatilDialogRef" />
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import _ from "lodash"
import { CapitalPoolSubIdPage, CapitalPoolDetail, CapitalPoolMonthExpiryRebatePage } from '/@/api/finance';
import { handleEmpty, getUrl } from "/@/utils/other";
import { useRouter } from 'vue-router'
import { Local } from '/@/utils/storage';
import { getContractorList } from '/@/api/purchase/index';

// 引入组件
const NewTable = defineAsyncComponent(() => import('/@/components/newTable/index.vue'))
const ReChargeDialog = defineAsyncComponent(() => import('/@/views/dealerClient/dealerCapitalPool/common/rechargeDialog.vue'))
// const ChangeDialog = defineAsyncComponent(() => import('/@/views/financialCenter/storeCapitalPools/dialog.vue'))

const OrderDialog = defineAsyncComponent(() => import('/@/views/financialCenter/storeCapitalPools/orderDialog.vue'))
const AfterOrderDialog = defineAsyncComponent(() => import('/@/views/financialCenter/storeCapitalPools/AfterOrderDialog.vue'))
const financeDetailDialog = defineAsyncComponent(() => import('/@/views/financialCenter/storeCapitalPools/financeDetailDialog.vue'))

// 定义变量内容
const OrderDialogRef = ref()
const AfterOrderDialogRef = ref()
const financeDeatilDialogRef = ref()
const route = useRouter()
const time = ref([])
const searchInfoRef = ref(null)
const chargeRef = ref(null)
const searchInfo = reactive({
  capitalType: '',
  dealTypes: '',
  orderNo: '',
  afterSaleNo: '',
  dealStartTime: '',
  dealEndTime: ''
})
const searchParm = reactive({
  page: 1,
  size: 20,
  sort: 'desc',
  orderBy: 'id',
})
const state = reactive({
  tableData: [],
  loading: true,
  total: 0,
  price: '',
  subId: null,
  baseform: {},
  subIds: null,
  subIdList: [],
  show: true
})
//每月返利到期金额列表
const rebateList1 = ref([
  { id: 1, time: '2025-09-15', type: '返利金额到期总额', amount: 1300.00 },
  { id: 2, time: '2025-10-15', type: '返利金额到期总额', amount: 1000.00 },
  { id: 3, time: '2025-11-15', type: '返利金额到期总额', amount: 1000.00 },
  { id: 4, time: '2025-12-15', type: '返利金额到期总额', amount: 1000.00 },
  { id: 5, time: '2026-01-15', type: '返利金额到期总额', amount: 1000.00 },
  { id: 6, time: '2026-02-15', type: '返利金额到期总额', amount: 1000.00 },
  { id: 7, time: '2026-03-15', type: '返利金额到期总额', amount: 1000.00 },
  { id: 8, time: '2026-04-15', type: '返利金额到期总额', amount: 1000.00 },
  { id: 9, time: '2026-05-15', type: '返利金额到期总额', amount: 1000.00 },
  { id: 10, time: '2026-06-15', type: '返利金额到期总额', amount: 1000.00 },
]);
const rebateList = ref([]);
const formatTime = (timeStr) => {
  const date = new Date(timeStr);
  return `${date.getFullYear()}年${date.getMonth() + 1}月`;
};
const formatAmount = (row) => `¥${row.amount.toFixed(2)}`;



// 分页查询资金池月到期返利列表
CapitalPoolMonthExpiryRebatePage(state.subId, {
  page: 1,
  size: 10,
  sort: searchParm.sort,
  orderBy: searchParm.orderBy,
}).then(res => {
  if (res.code === 200) {
    rebateList.value = res.data.list;
    console.log('rebateList', rebateList.value);
  }
})



const tableHead = [
  {
    prop: 'balanceType', label: '变更金额类型', width: 120, fun(row) {
      const reflect = [
        { label: '资金池', value: 'BALANCE' },
        { label: '基础返利池', value: 'REBATE' },
        { label: '京东返利池', value: 'JD_REBATE' }
      ]
      return reflect.find(item => item.value === row.balanceType)?.label
    },
  },
  { prop: 'rebateBatch', label: '返利金额批次', width: 150 }, // 新增
  { prop: 'rebateStatus', label: '返利金额状态', width: 150 }, // 新增
  { prop: 'capitalType', label: '资金出入账类型', width: 180 },
  { prop: 'deductionType', label: '扣减类型', width: 120 }, // 新增
  { prop: 'remark', label: '明细', width: 300 },
  { prop: 'dealTime', label: '处理时间', width: 180 },
  { prop: 'expireDate', label: '到期日期', width: 180 }, // 新增
  { prop: 'orderNo', label: '关联订单号', width: 180, clickOrder: true, showTip: false },
  { prop: 'afterSaleNo', label: '关联售后单号', width: 180, clickOrderAfter: true, showTip: false },
  { prop: 'changeAmount', label: '金额变更' },
  {
    label: '变更后余额', minWidth: 180, headerAlign: 'center', align: 'center', fun(row) {
      return row.balanceType === 'BALANCE' ? row.balance : row.balanceType === 'REBATE' ? row.rebate : row.jdRebate;
    }
  },
  { prop: 'explainFirst', label: '返利类型', width: 120 }, // 新增
  { prop: 'explainSecond', label: '返利划分明细', width: 200 }, // 新增
  { prop: 'dealType', label: '处理事项', width: 180 },
  { prop: 'financeDetail', label: '充值/扣减明细', width: 180, clickFinanceDetail: true, showTip: false },
  { prop: 'createName', label: '操作人' },
]
let clonedata = {}

// 资金出入账类型
const returnTypeList = [
  {
    value: 'OUT',
    label: '出账',
  },
  {
    value: 'IN',
    label: '入账',
  }
]
// 资金池类型
const TypeList = [
  {
    value: 'BALANCE',
    label: '资金池',
  },
  {
    value: 'REBATE',
    label: '基础返利池',
  },
  {
    value: 'JD_REBATE',
    label: '京东返利池'
  }
]
// 处理事项
const returnStatus = [
  {
    value: 'ORDER',
    label: '下单扣款',
  },
  {
    value: 'ROLLBACK',
    label: '下单扣款驳回',
  },
  {
    value: 'MANUAL',
    label: '手动操作',
  },
  {
    value: 'CANCEL',
    label: '售后-取消订单',
  },
  {
    value: 'EDIT',
    label: '售后-修改订单退款',
  },
  {
    value: 'RETURN',
    label: '售后-退货退款',
  },
  {
    value: 'SUPPLY_RECHARGE',
    label: '经销商充值'
  },
  {
    value: 'EXCHANGE',
    label: '售后-换货'
  }
]
const getAuth = inject('getAuth')

// 初始化表格数据
const getTableData = () => {
  if (!getAuth('DealerCapitalPoolList')) {
    ElMessage.warning('请先分配查询权限')
    return false
  }
  state.loading = true;
  state.show = true
  let param = getUrl(searchParm)
  CapitalPoolSubIdPage(state.subId, param, handleEmpty(clonedata)).then(res => {
    if (res.code == 200) {
      state.tableData = res.list
      state.tableData = state.tableData.map(item => ({ ...item, financeDetail: "查看" }))
      state.total = res.total
      CapitalPoolDetail(state.subId).then(res => {
        if (res.code == 200) {
          state.baseform = _.cloneDeep(res.data)
          state.loading = false
        } else {
          state.loading = false
          ElMessage.error(res.msg)
        }
      })
    } else {
      ElMessage.error(res.msg)
      state.loading = false
    }
  })
}

// 充值扣减
const changePrice = (val, balanceType) => {
  let data = {
    type: val,
    name: state.baseform.subName,
    id: state.subId,
    balanceType: balanceType,
    price: state.baseform.balance
  }
  chargeRef.value.openDialog(data)
}
const changeType = (val) => {
  state.subId = val
  state.baseform = {}
  getTableData()
}

// 查询
const onQuery = () => {
  searchInfo.afterSaleNo = searchInfo.afterSaleNo && searchInfo.afterSaleNo.trim()
  searchInfo.orderNo = searchInfo.orderNo && searchInfo.orderNo.trim()
  searchInfo.dealStartTime = time.value && time.value[0]
  searchInfo.dealEndTime = time.value && time.value[1]
  searchParm.page = 1
  clonedata = _.cloneDeep(searchInfo)
  getTableData()
}
// 重置
const onReset = () => {
  searchParm.page = 1
  searchParm.size = 20
  time.value = []
  clonedata = {}
  searchInfoRef.value.resetFields()
  getTableData()
}
// 分页改变
const onHandleSizeChange = (val) => {
  searchParm.size = val;
  getTableData();
}
const onHandleCurrentChange = (val) => {
  searchParm.page = val;
  getTableData();
}
const onLook = (val, type) => { // 查看类型分流处理
  if (type == 'order') {
    // 门店和上样单分流
    if (val.startsWith('SY')) {
      let routeUrl = route.resolve({
        name: 'dealerSampleOrderDetail',
        query: {
          sampleOrderNo: val
        },
        params: {
          channel: 'agent'
        }
      })
      window.open(routeUrl.href, '_blank')
    } else {
      OrderDialogRef.value.openDialog(val)
    }
  } else if (type == 'afterSaleNo') {
    // 门店售后和上样单售后分流
    if (val.startsWith('ASSY')) {
      let routeUrl = route.resolve({
        name: 'Dealer_SAMPLE_AS_EDIT',
        params: {
          pageType: 'detail',
        },
        query: {
          id: val
        }
      })
      window.open(routeUrl.href, '_blank')
    } else {
      AfterOrderDialogRef.value.openDialog(val)
    }
  } else if (type == 'financeDetail') {
    financeDeatilDialogRef.value.openDialog(val)
  }
}
function getContractor(params = {}) {
  getContractorList(params).then(res => {
    if (res.code == 200) {

      let result = res.data.filter(obj => Local.get('subIds').some(id => id == obj.id));
      let array = result.filter((item) => item.type == '经销')

      state.subIdList = array
      state.subId = array && array[0].id || null
      getTableData()
    } else {
      // ElMessage.warning('请先咨询财务开通资金池')
      // state.show = false
      state.subIdList = []
    }
  })
}

// 页面加载时
onMounted(() => {
  getContractor()
  console.log(state.subId)
  CapitalPoolMonthExpiryRebatePage()
});
</script>

<style scoped lang="scss">
.purchase-container {
  background: #f8f8f8;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light, #ebeef5);
  padding: 8px !important;
  position: absolute;
  left: 0;
  top: 0;
  display: flex;
  flex-direction: column;
  flex: 1;

  .purchase-padding {
    padding: 10px 10px 0;
    background: var(--el-color-white);

    .system-user-search {
      overflow: hidden;
    }

    .balance-poul {
      background-color: #FBFBFB;
      border: 1px solid #E1E1E1;
      border-radius: 10px;
      color: #606266;
      margin-bottom: 10px;
      padding: 8px 8px 20px;

      .main {
        display: flex;
        align-items: flex-start;
        margin-top: 18px;

        .priceBox {
          display: flex;
          flex: 1;
          align-self: stretch;
          // padding: 15px 15px 0 0;
          border-left: 2px solid #E1E1E1;
          padding: 0 18px;

          .priceBox-left {
            flex: 2;

            .btnlist {

              margin: 20px 0;
              align-items: center;
              justify-content: center;
              text-indent: 2em;
              flex-wrap: wrap;

              .price {
                font-size: 26px;
                font-weight: bold;
              }

              .w80 {
                width: 80px !important;
              }
            }
          }

          .priceBox-right {
            flex: 3;
            display: flex;

            .priceButton {
              display: flex;
              margin-left: auto;
              align-self: center
            }

            .rebate {
              width: 100%;
              height: 120px;

              display: flex;
              align-items: center;
              background-color: rgb(236, 245, 255);
              border-radius: 8px;

              .scrollbar {
                width: 100%;
                padding: 0 10px 0 20px;
              }

              .rebate-item {
                height: auto;
                min-height: 25px;
                display: flex;
                align-items: center;
                gap: 8px;
              }

              /* 蓝圆点样式 */
              .blue-dot {
                width: 8px;
                height: 8px;
                background-color: #409eff;
                border-radius: 50%;
                flex-shrink: 0;
              }

              /* 蓝色文本样式 */
              .text-blue {
                color: #606266;
                font-size: 13px;
              }
            }


          }

        }

        .priceBox:first-of-type {
          border-left: none;
        }

      }
    }
  }
}

.query-area {
  &_pool {
    width: 100%;
    display: grid;
    grid-column-gap: 15px;
  }
}

//   width >= 1680px 5 columns
@media screen and (min-width: 1680px) {
  .query-area {
    &_pool {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}

// width >= 1366px && width < 1680px 4 columns
@media screen and (min-width: 1366px) and (max-width: 1680px) {
  .query-area {
    &_pool {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}

//   width >= 1024px && width < 1366px 3 columns
@media screen and (min-width: 1024px) and (max-width: 1366px) {
  .query-area {
    &_pool {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}

// width >= 576px && width < 1024px 2 columns
@media screen and (min-width: 876px) and (max-width: 1024px) {
  .query-area {
    &_pool {
      grid-template-columns: repeat(2, 1fr)
    }
  }
}

// width < 576px 1 columns
@media screen and (max-width: 876px) {
  .query-area {
    &_pool {
      grid-template-columns: repeat(1, 1fr);

      .centerLine {
        display: none;
      }
    }
  }
}
</style>


// 分页查询资金池月到期返利列表
export function CapitalPoolMonthExpiryRebatePage(subjectId, data) {
	return request({
		url: BASE_API + `/api/v2/pri/capital/pool/${subjectId}/monthly/expiry_rebate/page`,
		data,
	})
}